package com.itheima.marking_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.itheima.marking_system.config.JwtConfig;
import com.itheima.marking_system.pojo.common.BaseContext;
import com.itheima.marking_system.pojo.common.CustomException;
import com.itheima.marking_system.pojo.common.Jwt;
import com.itheima.marking_system.pojo.common.R;
import com.itheima.marking_system.pojo.entity.TeacherEntity;
import com.itheima.marking_system.service.TeacherService;
import com.itheima.marking_system.utils.jwt.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/teacher")
@Slf4j
@Api(tags = "【教师管理】")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private JwtConfig jwtConfig;
    @ApiModelProperty(value = "老师登录", notes = "老师登录接口")
    @PostMapping("/login")
    public R<Jwt> login(@RequestBody TeacherEntity teacherEntity, HttpServletRequest request) {
        log.info("老师登录接口，参数：{}", teacherEntity);
        String password = teacherEntity.getPassword();
        String phone = teacherEntity.getPhone();
        boolean isPhone = teacherService.checkPhone(phone);
        if (!isPhone) {
            throw new CustomException("手机号码格式不正确");
        }
        LambdaQueryWrapper<TeacherEntity> queryWrapper = new LambdaQueryWrapper<TeacherEntity>();
        queryWrapper.eq(TeacherEntity::getPhone, phone);
        TeacherEntity teacher = teacherService.getOne(queryWrapper);
        if (teacher == null) {
            throw new RuntimeException("手机号码未注册");
        }
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5Password.equals(teacher.getPassword())) {
            return R.error("用户名或密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("teacherId", teacher.getId());

        String jwt = JwtUtils.generateToken(map, jwtConfig.getExpiration(), jwtConfig.getSecret());
        Jwt jwtToken = Jwt.builder()
                .id(teacher.getId())
                .name(teacher.getName())
               .token(jwt)
               .build();

        return R.success(jwtToken);
    }


    @ApiModelProperty(value = "老师注册", notes = "老师注册接口")
    @PostMapping("/register")
    public R<String> register(@RequestBody TeacherEntity teacherEntity) {
        log.info("老师注册接口，参数：{}", teacherEntity);
        String password = teacherEntity.getPassword();
        String phone = teacherEntity.getPhone();
        boolean isPhone = teacherService.checkPhone(phone);
        if (!isPhone) {
            throw new RuntimeException("手机号码格式不正确");
        }
        LambdaQueryWrapper<TeacherEntity> queryWrapper = new LambdaQueryWrapper<TeacherEntity>();
        queryWrapper.eq(TeacherEntity::getPhone, phone);
        TeacherEntity teacher = teacherService.getOne(queryWrapper);
        if (teacher != null) {
            return R.error("手机号码已注册");
        }
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        TeacherEntity newTeacher = new TeacherEntity();
        newTeacher.setPhone(phone);
        newTeacher.setPassword(md5Password);
        teacherService.save(newTeacher);
        return R.success("注册成功");
    }


    @ApiModelProperty(value = "老师退出", notes = "老师退出接口")
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("teacherId");
        return R.success("退出成功");
    }
}
